package cc.catface.api.global.interceptor.readbody;

import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**解决request流只能读取一次的问题;step1:包装类:可重复读request输入流*/
@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {

    /**存储body数据的容器*/
    private final byte[] body;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        //将body数据存储起来
        body = getBodyString(request).getBytes(Charset.defaultCharset());
    }

    /**获取请求body*/
    @SneakyThrows
    public String getBodyString(final ServletRequest request) {
        return inputStream2String(request.getInputStream());
    }

    /**获取请求body*/
    public String getBodyString() {
        final InputStream inputStream = new ByteArrayInputStream(body);
        return inputStream2String(inputStream);
    }

    /**将inputStream里的数据读取出来并转换成字符串*/
    @SneakyThrows
    private String inputStream2String(InputStream inputStream) {
        StringBuilder sb = new StringBuilder();
        @Cleanup BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() {
                return inputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {}
        };
    }
}
